package apis

import (
	"leechbox_gis/logic"
	"leechbox_gis/models"
	"leechbox_gis/tools"

	"github.com/kataras/iris/v12"
)

type ExecuteAPI struct {
	Ctx iris.Context
}

// 执行命令
func (that *ExecuteAPI) Post() *models.ResponseBody {
	input := &models.CommandDTO{}
	if err := that.Ctx.ReadJSON(input); err != nil {
		return tools.Failed(403, err.Error())
	}

	if input.Async {
		if res, err := logic.ExecuteLogic.ExecuteCommandAsync(input.RandomCode, input.Command, input.Args...); nil != err {
			return tools.Failed(500, err.Error())
		} else {
			return tools.Success(res)
		}
	}

	if res, err := logic.ExecuteLogic.ExecuteCommandSync(input.Command, input.Args...); nil != err {
		return tools.Failed(500, err.Error())
	} else {
		return tools.Success(res)
	}
}

// 获取异步执行命令的结果
func (that *ExecuteAPI) GetResult() *models.ResponseBody {
	randomCode := that.Ctx.URLParam("code")
	content := logic.ExecuteLogic.GetAsyncExecuteResult(randomCode)
	return tools.Success(content)
}
